<template>
  <div class="community-page">
    <div class="container">
      <div class="page-header">
        <h1 class="page-title">社区</h1>
      </div>
      
      <!-- 挑战任务部分 -->
      <div class="challenge-section" style="margin-bottom: 30px;">
        <div class="section-header">
          <h2 class="section-title">本月挑战</h2>
          <button class="more-tasks-btn" @click="navigateToAllChallenges">
            <span>更多任务</span>
            <i class="fas fa-angle-right"></i>
          </button>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="challengesLoading" class="challenges-loading">
          <div class="spinner"></div>
          <p>正在加载挑战...</p>
        </div>
        
        <!-- 没有挑战数据时的空状态 -->
        <div v-else-if="topChallenges.length === 0" class="challenges-empty">
          <i class="fas fa-tasks"></i>
          <p>暂无挑战任务</p>
        </div>
        
        <!-- 挑战列表 -->
        <div v-else class="challenges-container">
          <div 
            v-for="challenge in topChallenges" 
            :key="challenge.id" 
            class="challenge-card" 
            :class="[`gradient-${challenge.id % 5}`]"
            @click="navigateToChallenge(challenge.id)"
          >
            <div class="status-dot" :class="{ 'completed': challenge.completed }"></div>
            <button class="start-btn">即将开始</button>
            
            <div class="challenge-content">
              <h3 class="challenge-title">{{ challenge.title }}</h3>
              <p class="challenge-description">{{ challenge.description }}</p>
              
              <div class="challenge-meta">
                <div class="challenge-tag">
                  {{ getTaskType(challenge) }}
                </div>
                <div class="challenge-dates">
                  2025-03-20 至 2025-04-04
                </div>
              </div>
              
              <div class="challenge-footer">
                <div class="challenge-participants">
                  <i class="fas fa-users"></i>
                  <span>{{ 10 + challenge.id * 5 }} 参与者</span>
                </div>
                <div class="challenge-points">
                  <i class="fas fa-award"></i>
                  <span>{{ challenge.points }} 积分</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 海绵宝宝风格的环保动画区域 -->
      <div class="eco-animation-container" style="margin-top: 0;">
        <div class="animation-title">
          <h2>碳减排小贴士</h2>
          <span>跟着海底好友一起学环保</span>
        </div>
        
        <div class="animation-scene">
          <!-- 海绵宝宝角色 -->
          <div class="character spongebob">
            <div class="character-bubble">
              <p>多骑自行车，少开车，减少碳排放！</p>
            </div>
          </div>
          
          <!-- 派大星角色 -->
          <div class="character patrick">
            <div class="character-bubble">
              <p>记得随手关灯，节约能源从我做起~</p>
            </div>
          </div>
          
          <!-- 章鱼哥角色 -->
          <div class="character squidward">
            <div class="character-bubble">
              <p>减少一次性餐具使用，保护海洋环境！</p>
            </div>
          </div>
          
          <!-- 海底场景元素 -->
          <div class="scene-element coral"></div>
          <div class="scene-element seaweed-1"></div>
          <div class="scene-element seaweed-2"></div>
          <div class="scene-element bubble bubble-1"></div>
          <div class="scene-element bubble bubble-2"></div>
          <div class="scene-element bubble bubble-3"></div>
          <div class="scene-element fish fish-1"></div>
          <div class="scene-element fish fish-2"></div>
        </div>
      </div>
      
      <div class="community-layout">
        <!-- 主要内容区域 -->
        <div class="community-main">
          <!-- 发布帖子区域 -->
          <div class="post-creator">
            <div class="post-input">
              <div class="user-avatar">
                <img v-if="userAvatar" :src="userAvatar" alt="用户头像" />
                <div v-else class="default-avatar" :style="{ background: generateAvatarColor(userName) }">
                  {{ getUserInitial(userName) }}
                </div>
              </div>
              <div class="input-area" @click="showPostForm = true">
                <span class="placeholder">分享你的减碳心得、经验或问题...</span>
              </div>
            </div>
            
            <div v-if="showPostForm" class="post-form">
              <div class="form-header">发布帖子</div>
              <div class="form-body">
                <input v-model="postTitle" type="text" class="post-title-input" placeholder="标题（选填）">
                <textarea v-model="postContent" class="post-content-input" placeholder="分享你的减碳心得、经验或问题..."></textarea>
                
                <div class="post-categories">
                  <div 
                    v-for="category in categories" 
                    :key="category.id" 
                    :class="['category-tag', { active: selectedCategory === category.id }]"
                    @click="selectedCategory = category.id"
                  >
                    {{ category.name }}
                  </div>
                </div>
              </div>
              <div class="form-footer">
                <button class="cancel-btn" @click="cancelPost">取消</button>
                <button class="publish-btn" :disabled="!canPublish" @click="publishPost">发布</button>
              </div>
            </div>
          </div>
          
          <!-- 帖子列表 -->
          <div class="posts-list">
            <div class="list-header">
              <h3>最新帖子</h3>
              <div class="post-filters">
                <span :class="{ active: currentFilter === 'all' }" @click="setFilter('all')">全部</span>
                <span :class="{ active: currentFilter === 'hot' }" @click="setFilter('hot')">热门</span>
                <span :class="{ active: currentFilter === 'following' }" @click="setFilter('following')">关注</span>
              </div>
            </div>
            
            <div v-if="loading" class="loading-posts">
              <div class="spinner"></div>
              <p>加载中...</p>
            </div>
            
            <div v-else-if="posts.length === 0" class="empty-posts">
              <i class="fas fa-comments"></i>
              <p>暂无帖子，成为第一个发帖的人吧！</p>
            </div>
            
            <div v-else class="posts-container">
              <div v-for="post in posts" :key="post.id" class="post-card">
                <div class="post-header">
                  <div class="post-author">
                    <div class="user-avatar small">
                      <img v-if="post.author.avatar" :src="post.author.avatar" alt="作者头像" />
                      <div v-else class="default-avatar" :style="{ background: generateAvatarColor(post.author.name) }">
                        {{ getUserInitial(post.author.name) }}
                      </div>
                    </div>
                    <div class="author-info">
                      <div class="author-name">{{ post.author.name }}</div>
                      <div class="post-meta">{{ formatDate(post.createdAt) }}</div>
                    </div>
                  </div>
                  <div class="post-category" v-if="post.category">{{ getCategoryName(post.category) }}</div>
                </div>
                <div class="post-content">
                  <h3 v-if="post.title" class="post-title">{{ post.title }}</h3>
                  <p class="post-text">{{ post.content }}</p>
                </div>
                <div class="post-actions">
                  <div class="action-btn" @click="likePost(post)">
                    <i :class="['fas', 'fa-thumbs-up', { 'active': post.liked }]"></i>
                    <span>{{ post.likes || 0 }}</span>
                  </div>
                  <div class="action-btn" @click="showComments(post)">
                    <i class="fas fa-comment"></i>
                    <span>{{ post.comments || 0 }}</span>
                  </div>
                  <div class="action-btn" @click="sharePost(post)">
                    <i class="fas fa-share-alt"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 侧边栏 -->
        <div class="community-sidebar">
          <!-- 积分排行榜 -->
          <user-leaderboard :limit="10" />
          
          <!-- 热门话题 -->
          <div class="hot-topics sidebar-card">
            <h3 class="sidebar-title">热门话题</h3>
            <div class="topic-list">
              <div v-for="topic in hotTopics" :key="topic.id" class="topic-item" @click="selectTopic(topic)">
                <div class="topic-name">{{ topic.name }}</div>
                <div class="topic-count">{{ topic.postCount }}个帖子</div>
              </div>
              <div v-if="hotTopics.length === 0" class="empty-state small">
                暂无热门话题
              </div>
            </div>
          </div>
          
          <!-- 社区公告 -->
          <div class="community-announcement sidebar-card">
            <h3 class="sidebar-title">社区公告</h3>
            <div class="announcement-content">
              <div v-if="announcement" class="announcement">
                <div class="announcement-title">{{ announcement.title }}</div>
                <div class="announcement-text">{{ announcement.content }}</div>
                <div class="announcement-date">{{ formatDate(announcement.date) }}</div>
              </div>
              <div v-else class="empty-state small">
                暂无公告
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import UserLeaderboard from '@/components/Leaderboard.vue';
import { getTaskList } from '@/api/task';

export default {
  name: 'CommunityPage',
  components: {
    UserLeaderboard
  },
  data() {
    return {
      // 挑战任务
      challenges: [],
      challengesPage: 1,
      challengesPageSize: 3,
      challengesLoading: false,
      
      // 动画区域数据
      ecoTips: [
        "使用可重复使用的购物袋，减少塑料袋使用",
        "选择当季、本地食材，减少食物运输的碳排放",
        "尽量步行或骑自行车替代短途驾车",
        "使用节能灯泡和电器，减少能源消耗",
        "减少肉类消费，尝试多吃素食",
        "洗澡时间控制在5分钟内，节约用水",
        "选择无包装或简约包装的产品",
        "购买二手物品，延长产品生命周期",
        "自带水杯，拒绝一次性塑料杯",
        "将不用的电器彻底关闭，不要留在待机状态"
      ],
      currentEcoTip: "",
      
      // 用户信息
      userName: '',
      userAvatar: '',
      
      // 发帖相关
      showPostForm: false,
      postTitle: '',
      postContent: '',
      selectedCategory: null,
      
      // 帖子列表相关
      loading: false,
      posts: [],
      currentFilter: 'all',
      
      // 热门话题
      hotTopics: [
        { id: 1, name: '#绿色出行', postCount: 128 },
        { id: 2, name: '#食物减碳', postCount: 96 },
        { id: 3, name: '#节能家电', postCount: 67 },
        { id: 4, name: '#可持续时尚', postCount: 45 },
        { id: 5, name: '#零浪费生活', postCount: 38 },
      ],
      
      // 社区公告
      announcement: {
        title: '社区规则更新',
        content: '亲爱的减碳伙伴们，为了维护良好的社区环境，我们更新了社区规则，请大家遵守！',
        date: new Date(2023, 10, 15)
      },
      
      // 帖子分类
      categories: [
        { id: 1, name: '绿色出行' },
        { id: 2, name: '食物减碳' },
        { id: 3, name: '节能家电' },
        { id: 4, name: '可持续时尚' },
        { id: 5, name: '零浪费生活' },
        { id: 6, name: '问答' },
        { id: 7, name: '经验分享' },
        { id: 8, name: '其他' }
      ]
    };
  },
  computed: {
    canPublish() {
      return this.postContent.trim().length > 0;
    },
    topChallenges() {
      // 排序并只返回前三个挑战
      return [...this.challenges]
        .sort((a, b) => a.id - b.id)
        .slice(0, 3);
    }
  },
  created() {
    this.fetchUserInfo();
    this.fetchPosts();
    this.fetchChallenges();
  },
  // 添加路由钩子函数
  beforeRouteEnter(to, from, next) {
    next(vm => {
      // 检查是否从挑战页面导航过来
      if (from.path && (from.path.includes('/challenge') || from.path.includes('/challenges'))) {
        // 强制页面重新渲染
        setTimeout(() => {
          window.scrollTo(0, 0);
          // 刷新挑战数据
          vm.fetchChallenges();
        }, 50);
      }
    });
  },
  methods: {
    // 环保小贴士相关
    showRandomEcoTip() {
      const randomIndex = Math.floor(Math.random() * this.ecoTips.length);
      this.currentEcoTip = this.ecoTips[randomIndex];
      
      // 显示提示弹窗
      this.$notify({
        title: '环保小贴士',
        message: this.currentEcoTip,
        type: 'success',
        duration: 4000
      });
    },
    
    // 挑战相关
    fetchChallenges() {
      this.challengesLoading = true;
      
      // 准备API请求参数
      const params = {
        pageNo: this.challengesPage,
        pageSize: this.challengesPageSize
      };
      
      // 调用API获取数据
      getTaskList(params)
        .then(response => {
          console.log('任务数据响应:', response);
          
          // 处理不同响应格式的情况
          let taskList = [];
          
          if (response.code === 200) {
            // 第一种情况：标准响应结构
            if (response.data && response.data.list) {
              taskList = response.data.list;
            } 
            // 第二种情况：data 是数组
            else if (Array.isArray(response.data)) {
              taskList = response.data;
            }
            // 第三种情况：data.result 是数组
            else if (response.data && Array.isArray(response.data.result)) {
              taskList = response.data.result;
            }
            // 第四种情况：data 对象下有其他字段
            else if (response.data && typeof response.data === 'object') {
              // 尝试在 data 对象中查找可能的数组字段
              const possibleArrayKeys = Object.keys(response.data).filter(key => 
                Array.isArray(response.data[key]) && response.data[key].length > 0
              );
              
              if (possibleArrayKeys.length > 0) {
                // 使用第一个找到的数组
                taskList = response.data[possibleArrayKeys[0]];
              }
            }
          } else if (response.data && response.data.success && response.data.data) {
            // 处理嵌套响应结构
            const innerData = response.data.data;
            if (Array.isArray(innerData)) {
              taskList = innerData;
            } else if (innerData.list) {
              taskList = innerData.list;
            }
          }
          
          if (taskList.length > 0) {
            console.log('找到任务列表:', taskList);
            
            // 将API响应数据映射到组件所需的数据结构
            this.challenges = taskList.map(task => {
              // 确保属性名称正确
              const taskData = {
                id: task.id,
                title: task.taskName || task.title || '',
                description: task.taskDescription || task.description || '',
                icon: this.getTaskIcon(task.taskType || task.type || ''),
                progress: this.calculateTaskProgress(task),
                points: task.pointReward || task.points || 0,
                carbon: task.carbonReduction || task.carbon || Math.floor((task.pointReward || task.points || 0) / 2),
                joined: task.isParticipating || task.joined || false,
                completed: task.taskStatus === 2 || task.status === 2 || task.completed || false
              };
              
              console.log('处理任务数据:', taskData);
              return taskData;
            });
          } else {
            console.warn('未找到任务列表数据');
            this.challenges = [];
          }
        })
        .catch(error => {
          console.error('获取任务列表失败:', error);
          this.challenges = [];
          
          // 非生产环境使用模拟数据
          if (process.env.NODE_ENV !== 'production') {
            console.log('使用模拟数据');
            this.challenges = [
              {
                id: 1,
                title: '绿色出行30天',
                description: '连续30天使用公共交通、骑行或步行代替私家车出行',
                icon: 'fas fa-bicycle',
                progress: 65,
                points: 300,
                carbon: 120,
                joined: true,
                completed: false
              },
              {
                id: 2,
                title: '无肉周一',
                description: '连续4周的周一全天不食用肉类，选择植物性饮食',
                icon: 'fas fa-seedling',
                progress: 100,
                points: 200,
                carbon: 80,
                joined: true,
                completed: true
              },
              {
                id: 3,
                title: '家庭节能挑战',
                description: '一个月内减少家庭用电15%，记录并分享省电技巧',
                icon: 'fas fa-bolt',
                progress: 0,
                points: 350,
                carbon: 150,
                joined: false,
                completed: false
              }
            ];
          }
        })
        .finally(() => {
          this.challengesLoading = false;
        });
    },
    
    // 计算任务进度
    calculateTaskProgress(task) {
      // 处理直接给出进度的情况
      if (task.progress !== undefined) {
        return parseInt(task.progress);
      }
      
      // 任务已完成，返回100%
      if (task.taskStatus === 2 || task.status === 2 || task.completed) {
        return 100;
      }
      
      // 任务未开始，返回0%
      if (task.taskStatus === 0 || task.status === 0) {
        return 0;
      }
      
      // 任务进行中，根据日期计算进度
      const startTime = task.startTime || task.startDate;
      const endTime = task.endTime || task.endDate;
      
      if (startTime && endTime) {
        const startDate = new Date(startTime);
        const endDate = new Date(endTime);
        const today = new Date();
        
        // 如果日期格式有问题，返回默认值50%
        if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
          console.warn('日期格式错误:', startTime, endTime);
          return 50;
        }
        
        // 如果今天在开始日期之前，进度为0
        if (today < startDate) return 0;
        
        // 如果今天在结束日期之后，进度为100
        if (today > endDate) return 100;
        
        // 计算已过天数和总天数
        const totalDays = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24));
        const passedDays = Math.ceil((today - startDate) / (1000 * 60 * 60 * 24));
        
        // 计算进度百分比
        const progress = Math.round((passedDays / totalDays) * 100);
        return Math.min(Math.max(progress, 0), 100); // 确保进度在0-100之间
      }
      
      // 如果没有日期信息，默认返回进行中状态，进度50%
      return 50;
    },
    
    // 根据任务类型获取对应图标
    getTaskIcon(taskType) {
      // 处理任务类型为null或undefined的情况
      if (!taskType) {
        return 'fas fa-tasks';
      }
      
      const iconMap = {
        '低碳生活': 'fas fa-leaf',
        '绿色出行': 'fas fa-bicycle',
        '资源回收': 'fas fa-recycle',
        '节能减排': 'fas fa-bolt',
        '植物饮食': 'fas fa-seedling',
        '环保宣传': 'fas fa-bullhorn'
      };
      
      return iconMap[taskType] || 'fas fa-tasks';
    },
    
    // 获取任务分类名称
    getTaskType(challenge) {
      const typeMap = {
        'fas fa-leaf': '健康生活',
        'fas fa-bicycle': '绿色出行',
        'fas fa-recycle': '资源回收',
        'fas fa-bolt': '节能减排',
        'fas fa-seedling': '健康饮食',
        'fas fa-bullhorn': '环保宣传',
        'fas fa-tasks': '低碳活动'
      };
      
      return typeMap[challenge.icon] || '低碳活动';
    },
    
    // 导航到挑战详情页
    navigateToChallenge(challengeId) {
      // 检查路由是否已配置
      const hasRouter = this.$router !== undefined;
      
      if (hasRouter) {
        // 使用Vue Router导航
        this.$router.push(`/challenge/${challengeId}`);
      } else {
        // 使用普通导航
        window.location.href = `/challenge/${challengeId}`;
      }
    },
    
    // 导航到挑战页面（显示所有挑战）
    navigateToAllChallenges() {
      const hasRouter = this.$router !== undefined;
      
      if (hasRouter) {
        this.$router.push('/challenges');
      } else {
        window.location.href = '/challenges';
      }
    },
    
    // 用户相关
    getUserInitial(userName) {
      if (!userName) return '用';
      const name = userName.trim();
      if (/[\u4e00-\u9fa5]/.test(name)) {
        return name.charAt(0);
      }
      return name.charAt(0).toUpperCase();
    },
    generateAvatarColor(username) {
      if (!username) return 'linear-gradient(135deg, #42b983, #2c3e50)';
      
      let hash = 0;
      for (let i = 0; i < username.length; i++) {
        hash = username.charCodeAt(i) + ((hash << 5) - hash);
      }
      hash = Math.abs(hash);
      
      const hue1 = hash % 360;
      const hue2 = (hash * 7) % 360;
      
      return `linear-gradient(135deg, hsl(${hue1}, 70%, 60%), hsl(${hue2}, 70%, 60%))`;
    },
    fetchUserInfo() {
      // 这里应该从用户状态或API获取用户信息
      this.userName = localStorage.getItem('userName') || '用户';
      this.userAvatar = localStorage.getItem('userAvatar') || '';
    },
    
    // 帖子相关
    fetchPosts() {
      this.loading = true;
      
      // 模拟API请求
      setTimeout(() => {
        // 这里应该是实际的API调用
        this.posts = [
          {
            id: 1,
            title: '我的绿色出行一个月总结',
            content: '最近一个月我完全使用公共交通和自行车出行，不仅减少了碳排放，还发现了很多城市里的美丽风景！',
            createdAt: new Date(2023, 10, 25),
            likes: 42,
            comments: 8,
            liked: false,
            category: 1,
            author: {
              name: '绿色先锋',
              avatar: ''
            }
          },
          {
            id: 2,
            title: '',
            content: '有人可以推荐一些好用的节能家电吗？准备装修新家，想从一开始就做到环保节能。',
            createdAt: new Date(2023, 10, 24),
            likes: 18,
            comments: 15,
            liked: true,
            category: 6,
            author: {
              name: '新家主人',
              avatar: ''
            }
          },
          {
            id: 3,
            title: '减碳食谱分享：蔬菜沙拉',
            content: '今天分享一个简单的蔬菜沙拉食谱，完全素食，碳足迹非常低，而且营养丰富！用本地时令蔬菜制作，味道鲜美。',
            createdAt: new Date(2023, 10, 23),
            likes: 56,
            comments: 12,
            liked: false,
            category: 2,
            author: {
              name: '素食达人',
              avatar: ''
            }
          }
        ];
        
        this.loading = false;
      }, 1000);
    },
    setFilter(filter) {
      if (this.currentFilter === filter) return;
      
      this.currentFilter = filter;
      this.fetchPosts(); // 重新获取帖子
    },
    getCategoryName(categoryId) {
      const category = this.categories.find(c => c.id === categoryId);
      return category ? category.name : '';
    },
    formatDate(date) {
      if (!date) return '';
      
      const now = new Date();
      const diff = now - new Date(date);
      
      // 不到1小时
      if (diff < 3600000) {
        const minutes = Math.floor(diff / 60000);
        return `${minutes}分钟前`;
      }
      
      // 不到24小时
      if (diff < 86400000) {
        const hours = Math.floor(diff / 3600000);
        return `${hours}小时前`;
      }
      
      // 不到7天
      if (diff < 604800000) {
        const days = Math.floor(diff / 86400000);
        return `${days}天前`;
      }
      
      // 超过7天显示日期
      const d = new Date(date);
      return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`;
    },
    
    // 帖子互动
    likePost(post) {
      post.liked = !post.liked;
      post.likes += post.liked ? 1 : -1;
      
      // 这里应该调用API来保存点赞状态
    },
    showComments(post) {
      // 打开评论区或跳转到帖子详情页
      console.log('Show comments for post', post.id);
    },
    sharePost(post) {
      // 显示分享选项
      console.log('Share post', post.id);
    },
    
    // 热门话题
    selectTopic(topic) {
      console.log('Select topic', topic.name);
      // 可以根据话题筛选帖子
    },
    
    // 发帖相关
    cancelPost() {
      this.showPostForm = false;
      this.postTitle = '';
      this.postContent = '';
      this.selectedCategory = null;
    },
    publishPost() {
      if (!this.canPublish) return;
      
      // 这里应该调用API发布帖子
      console.log('Publishing post:', {
        title: this.postTitle,
        content: this.postContent,
        category: this.selectedCategory
      });
      
      // 模拟发布成功
      this.posts.unshift({
        id: Date.now(),
        title: this.postTitle,
        content: this.postContent,
        createdAt: new Date(),
        likes: 0,
        comments: 0,
        liked: false,
        category: this.selectedCategory,
        author: {
          name: this.userName,
          avatar: this.userAvatar
        }
      });
      
      this.cancelPost();
    }
  },
};
</script>

<style scoped>
.community-page {
  padding: 30px 0;
  min-height: 100vh; /* 确保页面至少占满整个视口高度 */
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 28px;
  color: #333;
  margin-bottom: 0;
}

/* 挑战任务区域样式 */
.challenge-section {
  margin-bottom: 30px !important; /* 强制设置底部间距 */
  position: relative; /* 添加定位上下文 */
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 22px;
  color: #333;
  position: relative;
  font-weight: 500;
  margin: 0;
}

.section-title:after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 0;
  width: 40px;
  height: 3px;
  background-color: #4CAF50;
  border-radius: 3px;
}

.more-tasks-btn {
  display: flex;
  align-items: center;
  background: none;
  border: none;
  color: #4CAF50;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  padding: 6px 12px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.more-tasks-btn:hover {
  background-color: rgba(76, 175, 80, 0.1);
}

.more-tasks-btn i {
  margin-left: 5px;
}

.challenges-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.challenge-card {
  height: 250px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  padding: 0;
}

.challenge-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
}

.gradient-0 {
  background: linear-gradient(135deg, #66BB6A 0%, #43A047 100%);
}

.gradient-1 {
  background: linear-gradient(135deg, #42A5F5 0%, #1E88E5 100%);
}

.gradient-2 {
  background: linear-gradient(135deg, #AB47BC 0%, #8E24AA 100%);
}

.gradient-3 {
  background: linear-gradient(135deg, #26C6DA 0%, #00ACC1 100%);
}

.gradient-4 {
  background: linear-gradient(135deg, #FFA726 0%, #FB8C00 100%);
}

.status-dot {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #FFFFFF;
}

.status-dot.completed {
  background-color: #4CAF50;
}

.start-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  border: none;
  border-radius: 20px;
  padding: 6px 12px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.start-btn:hover {
  background-color: rgba(255, 255, 255, 0.3);
}

.challenge-content {
  padding: 50px 20px 20px;
  display: flex;
  flex-direction: column;
  height: 100%;
  color: white;
}

.challenge-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 8px;
}

.challenge-description {
  font-size: 14px;
  opacity: 0.9;
  margin: 0 0 auto;
  line-height: 1.4;
}

.challenge-meta {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.challenge-tag {
  background-color: rgba(255, 255, 255, 0.2);
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.challenge-dates {
  font-size: 12px;
  opacity: 0.9;
}

.challenge-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.challenge-participants, .challenge-points {
  display: flex;
  align-items: center;
  font-size: 13px;
}

.challenge-participants i, .challenge-points i {
  margin-right: 5px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
}

.community-layout {
  display: flex;
  gap: 30px;
}

.community-main {
  flex: 1;
  min-width: 0; /* 防止内容溢出 */
}

.community-sidebar {
  width: 320px;
  flex-shrink: 0;
}

/* 主要内容区域样式 */
.post-creator {
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow: hidden;
}

.post-input {
  display: flex;
  padding: 20px;
  align-items: center;
}

.user-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 15px;
  flex-shrink: 0;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-avatar.small {
  width: 36px;
  height: 36px;
}

.default-avatar {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  font-size: 18px;
}

.input-area {
  flex: 1;
  padding: 12px 15px;
  border: 1px solid #e0e0e0;
  border-radius: 24px;
  color: #666;
  cursor: text;
}

.placeholder {
  color: #999;
}

.post-form {
  background-color: #f9f9f9;
  padding: 0 0 20px;
  border-top: 1px solid #eee;
}

.form-header {
  padding: 15px 20px;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid #eee;
}

.form-body {
  padding: 20px;
}

.post-title-input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  margin-bottom: 15px;
  font-weight: 600;
  color: #333;
}

.post-content-input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  min-height: 120px;
  margin-bottom: 15px;
  resize: vertical;
}

.post-categories {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 15px;
}

.category-tag {
  padding: 6px 12px;
  background-color: #f0f0f0;
  border-radius: 16px;
  font-size: 13px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.category-tag:hover {
  background-color: #e0e0e0;
}

.category-tag.active {
  background-color: #4CAF50;
  color: white;
}

.form-footer {
  padding: 0 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn, .publish-btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  border: none;
  transition: background-color 0.2s;
}

.cancel-btn {
  background-color: transparent;
  color: #666;
}

.cancel-btn:hover {
  background-color: #f0f0f0;
}

.publish-btn {
  background-color: #4CAF50;
  color: white;
}

.publish-btn:hover {
  background-color: #43a047;
}

.publish-btn:disabled {
  background-color: #a5d6a7;
  cursor: not-allowed;
}

.posts-list {
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.list-header {
  padding: 16px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
}

.list-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.post-filters {
  display: flex;
  gap: 15px;
}

.post-filters span {
  cursor: pointer;
  color: #666;
  padding: 4px 8px;
  border-radius: 4px;
}

.post-filters span:hover {
  background-color: #f0f0f0;
}

.post-filters span.active {
  color: #4CAF50;
  font-weight: 500;
}

.loading-posts, .empty-posts {
  padding: 40px 0;
  text-align: center;
  color: #666;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 15px;
  border: 4px solid rgba(76, 175, 80, 0.1);
  border-radius: 50%;
  border-top-color: #4CAF50;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.empty-posts i {
  font-size: 36px;
  color: #bdbdbd;
  margin-bottom: 15px;
}

.post-card {
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.post-card:last-child {
  border-bottom: none;
}

.post-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.post-author {
  display: flex;
  align-items: center;
}

.author-info {
  display: flex;
  flex-direction: column;
}

.author-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 3px;
}

.post-meta {
  font-size: 12px;
  color: #999;
}

.post-category {
  background-color: #f0f0f0;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
}

.post-content {
  margin-bottom: 15px;
}

.post-title {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 18px;
  color: #333;
}

.post-text {
  color: #555;
  margin: 0;
  line-height: 1.5;
}

.post-actions {
  display: flex;
  gap: 20px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
  cursor: pointer;
}

.action-btn i {
  font-size: 16px;
}

.action-btn i.active {
  color: #4CAF50;
}

/* 侧边栏样式 */
.sidebar-card {
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 20px;
}

.sidebar-title {
  padding: 15px 20px;
  margin: 0;
  font-size: 16px;
  color: #333;
  border-bottom: 1px solid #eee;
}

.topic-list {
  padding: 10px 0;
}

.topic-item {
  padding: 10px 20px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.topic-item:hover {
  background-color: #f9f9f9;
}

.topic-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 3px;
}

.topic-count {
  font-size: 12px;
  color: #999;
}

.announcement-content {
  padding: 15px 20px;
}

.announcement-title {
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

.announcement-text {
  color: #666;
  margin-bottom: 10px;
  line-height: 1.5;
}

.announcement-date {
  font-size: 12px;
  color: #999;
}

.empty-state {
  text-align: center;
  padding: 30px;
  color: #999;
  font-style: italic;
}

.empty-state.small {
  padding: 15px;
  font-size: 13px;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .challenges-container {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .community-layout {
    flex-direction: column;
  }
  
  .community-sidebar {
    width: 100%;
    order: -1; /* 在移动端，排行榜显示在上方 */
  }
  
  .post-filters {
    gap: 10px;
  }
  
  .post-filters span {
    font-size: 13px;
  }
}

@media (max-width: 768px) {
  .challenges-container {
    grid-template-columns: 1fr;
  }
  
  .post-creator {
    margin-top: 20px;
  }
  
  .form-footer {
    padding: 0 15px;
  }
  
  .post-card {
    padding: 15px;
  }

  .post-header {
    flex-direction: column;
  }
  
  .post-category {
    align-self: flex-start;
    margin-top: 10px;
  }
}

/* 挑战任务加载状态 */
.challenges-loading, .challenges-empty {
  text-align: center;
  padding: 50px 0;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.challenges-loading .spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 15px;
  border: 4px solid rgba(76, 175, 80, 0.1);
  border-radius: 50%;
  border-top-color: #4CAF50;
  animation: spin 1s linear infinite;
}

.challenges-empty i {
  font-size: 40px;
  color: #e0e0e0;
  margin-bottom: 15px;
}

.challenges-empty p, .challenges-loading p {
  color: #999;
  font-size: 16px;
}

/* 海绵宝宝风格的环保动画区域 */
.eco-animation-container {
  background: linear-gradient(180deg, #64b5f6 0%, #1976d2 100%);
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 30px;
  margin-top: 0 !important; /* 确保顶部没有额外间距 */
  position: relative;
  overflow: hidden;
  min-height: 280px;
  box-shadow: 0 4px 20px rgba(25, 118, 210, 0.2);
}

.eco-animation-container:before {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><path fill="%23ffeb3b" opacity="0.2" d="M0,288L48,272C96,256,192,224,288,197.3C384,171,480,149,576,165.3C672,181,768,235,864,250.7C960,267,1056,245,1152,229.3C1248,213,1344,203,1392,197.3L1440,192L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"></path></svg>') bottom center no-repeat;
  background-size: cover;
  z-index: 1;
}

.animation-title {
  text-align: center;
  margin-bottom: 20px;
  position: relative;
  z-index: 2;
}

.animation-title h2 {
  color: white;
  font-size: 24px;
  margin: 0 0 5px;
  text-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.animation-title span {
  color: #fffde7;
  font-size: 14px;
}

.animation-scene {
  position: relative;
  height: 200px;
  z-index: 2;
}

/* 角色样式 */
.character {
  position: absolute;
  width: 80px;
  height: 100px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center bottom;
  transition: transform 0.3s ease;
}

.character:hover {
  transform: translateY(-10px);
}

.spongebob {
  left: 10%;
  bottom: 20px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 120"><rect x="20" y="20" width="60" height="80" rx="5" fill="%23ffeb3b"/><circle cx="35" cy="50" r="8" fill="white"/><circle cx="35" cy="50" r="4" fill="black"/><circle cx="65" cy="50" r="8" fill="white"/><circle cx="65" cy="50" r="4" fill="black"/><path d="M 40 70 Q 50 80 60 70" stroke="black" stroke-width="2" fill="none"/></svg>');
  animation: bobbing 3s ease-in-out infinite;
}

.patrick {
  left: 40%;
  bottom: 15px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 120"><path d="M 50 20 L 80 50 L 65 95 L 35 95 L 20 50 Z" fill="%23ec407a"/><circle cx="35" cy="50" r="6" fill="white"/><circle cx="35" cy="50" r="3" fill="black"/><circle cx="65" cy="50" r="6" fill="white"/><circle cx="65" cy="50" r="3" fill="black"/><path d="M 40 65 Q 50 60 60 65" stroke="black" stroke-width="2" fill="none"/></svg>');
  animation: bobbing 3.5s ease-in-out infinite 0.5s;
}

.squidward {
  right: 15%;
  bottom: 10px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 120"><ellipse cx="50" cy="40" rx="25" ry="30" fill="%2381c784"/><circle cx="40" cy="30" r="6" fill="white"/><circle cx="40" cy="30" r="3" fill="black"/><circle cx="60" cy="30" r="6" fill="white"/><circle cx="60" cy="30" r="3" fill="black"/><path d="M 40 50 Q 50 45 60 50" stroke="black" stroke-width="2" fill="none"/><path d="M 35 60 C 35 80, 65 80, 65 60" fill="%2381c784"/></svg>');
  animation: bobbing 4s ease-in-out infinite 1s;
}

.character-bubble {
  position: absolute;
  top: -60px;
  left: 50%;
  transform: translateX(-50%);
  background: white;
  border-radius: 10px;
  padding: 8px 12px;
  width: 140px;
  opacity: 0;
  transition: opacity 0.3s;
  box-shadow: 0 2px 6px rgba(0,0,0,0.2);
}

.character-bubble:after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  border-width: 10px 10px 0;
  border-style: solid;
  border-color: white transparent transparent;
}

.character-bubble p {
  margin: 0;
  font-size: 12px;
  color: #333;
  text-align: center;
}

.character:hover .character-bubble {
  opacity: 1;
}

/* 海底场景元素 */
.scene-element {
  position: absolute;
  background-repeat: no-repeat;
  background-size: contain;
  z-index: 1;
}

.coral {
  width: 100px;
  height: 70px;
  bottom: 0;
  left: 70%;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 70"><path d="M 20 70 C 20 50, 30 40, 30 20 C 30 40, 40 40, 40 70" fill="%23ef5350"/><path d="M 45 70 C 45 40, 55 30, 55 10 C 55 30, 65 40, 65 70" fill="%23ef9a9a"/><path d="M 70 70 C 70 50, 80 40, 80 30 C 80 50, 90 50, 90 70" fill="%23ef5350"/></svg>');
}

.seaweed-1 {
  width: 40px;
  height: 80px;
  bottom: 0;
  left: 5%;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 80"><path d="M 20 80 C 10 70, 30 60, 20 50 C 10 40, 30 30, 20 20 C 15 10, 25 5, 20 0" stroke="%234caf50" stroke-width="4" fill="none"/></svg>');
  animation: sway 4s ease-in-out infinite;
}

.seaweed-2 {
  width: 40px;
  height: 60px;
  bottom: 0;
  left: 85%;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 60"><path d="M 20 60 C 10 50, 30 40, 20 30 C 10 20, 30 10, 20 0" stroke="%234caf50" stroke-width="4" fill="none"/></svg>');
  animation: sway 5s ease-in-out infinite 1s;
}

.bubble {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.4);
  animation: rise 8s ease-in-out infinite;
}

.bubble-1 {
  left: 25%;
  bottom: 20px;
  animation-delay: 1s;
}

.bubble-2 {
  left: 60%;
  bottom: 40px;
  width: 15px;
  height: 15px;
  animation-delay: 3s;
}

.bubble-3 {
  left: 75%;
  bottom: 30px;
  width: 10px;
  height: 10px;
  animation-delay: 5s;
}

.fish {
  width: 30px;
  height: 20px;
  opacity: 0.8;
}

.fish-1 {
  top: 40%;
  left: -30px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 30 20"><path d="M 5 10 C 10 5, 20 5, 25 10 C 20 15, 10 15, 5 10 Z" fill="%23ffca28"/><circle cx="20" cy="8" r="2" fill="black"/><path d="M 5 10 L 0 5 L 0 15 Z" fill="%23ffca28"/></svg>');
  animation: swimRight 15s linear infinite;
}

.fish-2 {
  top: 60%;
  right: -30px;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 30 20"><path d="M 25 10 C 20 5, 10 5, 5 10 C 10 15, 20 15, 25 10 Z" fill="%2380deea"/><circle cx="10" cy="8" r="2" fill="black"/><path d="M 25 10 L 30 5 L 30 15 Z" fill="%2380deea"/></svg>');
  animation: swimLeft 18s linear infinite;
}

@keyframes bobbing {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-10px); }
}

@keyframes sway {
  0%, 100% { transform: rotate(0deg); }
  50% { transform: rotate(5deg); }
}

@keyframes rise {
  0% { 
    transform: translateY(0);
    opacity: 0; 
  }
  20% { opacity: 0.8; }
  100% { 
    transform: translateY(-150px);
    opacity: 0; 
  }
}

@keyframes swimRight {
  from { transform: translateX(0); }
  to { transform: translateX(calc(100vw + 30px)); }
}

@keyframes swimLeft {
  from { transform: translateX(0) scaleX(-1); }
  to { transform: translateX(calc(-100vw - 30px)) scaleX(-1); }
}
</style> 